package cn.getech.data.development.job.util

import java.io.{File, FileOutputStream}
import java.util.Properties

import com.sap.conn.jco.{JCoDestination, JCoDestinationManager}
import com.sap.conn.jco.ext.DestinationDataProvider

object SapConnUtils {
  private val ABAP_AS_POOLED = "ABAP_AS_WITH_POOL"

  def createDateFile(name: String,suffix: String,properties: Properties): Unit ={

    val file = new File(name +"."+ suffix)
    var fos: FileOutputStream = null

    if(file.exists()){
      file.deleteOnExit()
    }

    try{
      fos = new FileOutputStream(file,false)
      properties.store(fos,"for test...")
    }catch {
      case e: Exception => throw new RuntimeException(s"Failed To Create File error : ${e.toString}")
    }finally {
      if(fos!=null){
        fos.close()
      }
    }
  }

  def initProperties(sapConn:SapConn): Unit ={
    val prop = new Properties()
    val target: Int = sapConn.getIsGroup()

    if(target == 0){
      // SAP服务器
      prop.setProperty(DestinationDataProvider.JCO_ASHOST, sapConn.getJCO_ASHOST())
      // SAP系统编号
      prop.setProperty(DestinationDataProvider.JCO_SYSNR,  sapConn.getJCO_SYSNR())
    }else if(target == 1){
      prop.setProperty(DestinationDataProvider.JCO_MSHOST,  sapConn.getJCO_MHOST())
      prop.setProperty(DestinationDataProvider.JCO_GROUP,  sapConn.getJCO_GROUP())
      prop.setProperty(DestinationDataProvider.JCO_R3NAME,  sapConn.getJCO_R3NAME())
    }else{
      // SAP服务器
      prop.setProperty(DestinationDataProvider.JCO_ASHOST, sapConn.getJCO_ASHOST())
      // SAP系统编号
      prop.setProperty(DestinationDataProvider.JCO_SYSNR,  sapConn.getJCO_SYSNR())
    }
    // SAP集团
    prop.setProperty(DestinationDataProvider.JCO_CLIENT, sapConn.getJCO_CLIENT())
    // SAP用户名
    prop.setProperty(DestinationDataProvider.JCO_USER,   sapConn.getJCO_USER())
    // SAP密码
    prop.setProperty(DestinationDataProvider.JCO_PASSWD, sapConn.getJCO_PASSWD())
    // SAP登录语言
    prop.setProperty(DestinationDataProvider.JCO_LANG,   sapConn.getJCO_LANG())
    // SAP ROUTER
    //prop.setProperty(DestinationDataProvider.JCO_SAPROUTER, sapConn.getJCO_SAPROUTER())
    createDateFile(ABAP_AS_POOLED,"jcoDestination",prop)
  }

  def getSapConn(sapConn: SapConn): JCoDestination ={
    println("正在建立sap链接...")
    var destination: JCoDestination = null
    initProperties(sapConn)
    try{
      destination = JCoDestinationManager.getDestination(ABAP_AS_POOLED)
      destination.ping()
      println("成功建立sap链接...")
    }catch {
      case e: Exception => e.printStackTrace()
    }
    destination
  }
}
